<template>
	<view class="">
		<u-navbar :is-back="true" :custom-back="back" title="个人信息" :border-bottom="true"></u-navbar>
		<u-cell-group>
			<u-cell-item title="会员等级" :value="userLevel" :arrow="false"></u-cell-item>
			<u-cell-item :arrow="true" @click="chooseAvatar">
				<view class="flex align-center justify-between flex-sub">
					<view class="flex align-center flex-sub justify-between">
						<text class="padding-right" style="color:#606266">头像</text>
						<u-avatar :src="avatar" size="60"></u-avatar>
					</view>
				</view>
			</u-cell-item>
			<u-cell-item title="昵称" :value="nickname || '未设置'" :arrow="true" @click="editNickname"></u-cell-item>
			<u-cell-item title="手机号" :value="phone || '未绑定'" :arrow="false"></u-cell-item>
			<u-cell-item title="邮箱" :value="email || '未设置'" :arrow="true" @click="editEmail"></u-cell-item>
			<u-cell-item title="性别" :value="genderText" :arrow="true" @click="editGender"></u-cell-item>
			<u-cell-item title="生日" :value="birthday || '未设置'" :arrow="true" @click="editBirthday"></u-cell-item>
		</u-cell-group>
		
		<!-- 确定按钮 -->
		<view class="confirm-button-container">
			<u-button type="primary" :custom-style="confirmButtonStyle" @click="confirmAndBack">确定</u-button>
		</view>
		
		<u-toast ref="uToast" />
		
		<!-- 编辑昵称弹窗 -->
		<u-modal v-model="showNicknameModal" title="编辑昵称" :show-cancel-button="true" @confirm="saveNickname" @open="onNicknameModalOpen">
			<view class="modal-content">
				<u-input 
					ref="nicknameInput"
					v-model="editNicknameValue" 
					placeholder="请输入昵称" 
					maxlength="20" 
					:clearable="true"
					:focus="nicknameInputFocus"
					@focus="onNicknameInputFocus"
				></u-input>
			</view>
		</u-modal>
		
		<!-- 编辑邮箱弹窗 -->
		<u-modal v-model="showEmailModal" title="编辑邮箱" :show-cancel-button="true" @confirm="saveEmail">
			<view class="modal-content">
				<u-input v-model="editEmailValue" placeholder="请输入邮箱" type="text" :clearable="true"></u-input>
			</view>
		</u-modal>
		
		<!-- 编辑性别弹窗 -->
		<u-action-sheet v-model="showGenderSheet" :list="genderList" @click="selectGender"></u-action-sheet>
		
		<!-- 编辑生日弹窗 -->
		<u-picker v-model="showBirthdayPicker" mode="time" :params="birthdayParams" @confirm="saveBirthday"></u-picker>
	</view>
</template>

<script>
import $api from '../../api/user.js';

export default {
	data() {
		return {
			userId: null,
			avatar: require('../../static/image/user/avatar.jpg'),
			nickname: '',
			phone: '',
			email: '',
			gender: null, // 0-未知，1-男，2-女（与数据库一致）
			birthday: '',
			level: 1,
			
			// 编辑相关
			showNicknameModal: false,
			editNicknameValue: '',
			nicknameInputFocus: false, // 控制昵称输入框焦点
			showEmailModal: false,
			editEmailValue: '',
			showGenderSheet: false,
			genderList: [
				{ text: '未知', value: 0 },
				{ text: '男', value: 1 },
				{ text: '女', value: 2 }
			],
			showBirthdayPicker: false,
			birthdayParams: {
				year: true,
				month: true,
				day: true
			},
			// 确定按钮样式
			confirmButtonStyle: {
				width: '100%',
				height: '88rpx',
				borderRadius: '44rpx',
				fontSize: '32rpx',
				fontWeight: 'bold'
			}
		}
	},
	computed: {
		userLevel() {
			const levels = ['普通会员', '黄金会员', '白金会员', '钻石会员'];
			return levels[this.level - 1] || '普通会员';
		},
		genderText() {
			if (this.gender === null) return '未设置';
			const genders = ['未知', '男', '女']; // 0-未知，1-男，2-女
			return genders[this.gender] || '未设置';
		}
	},
	onLoad() {
		this.loadUserInfo();
	},
	created() {
		// 监听从裁剪页发布的事件，获得裁剪结果
		uni.$on('uAvatarCropper', path => {
			this.uploadAvatar(path);
		});
	},
	beforeDestroy() {
		// 移除事件监听
		uni.$off('uAvatarCropper');
	},
	methods: {
		// 加载用户信息
		loadUserInfo() {
			const user = uni.getStorageSync('user');
			if (!user || !user.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			this.userId = user.id;
			
			// 从本地存储加载用户信息
			this.avatar = user.avatar || require('../../static/image/user/avatar.jpg');
			this.nickname = user.nickname || '';
			this.phone = user.phone || '';
			this.email = user.email || '';
			this.gender = user.gender;
			this.birthday = user.birthday || '';
			this.level = user.level || 1;
			
			// 从服务器获取最新信息
			this.$api.getUserInfoById({
				userId: this.userId
			}).then(res => {
				if (res.data && res.data.code === 200) {
					const userData = res.data.data;
					if (userData) {
						this.avatar = userData.avatar || this.avatar;
						this.nickname = userData.nickname || '';
						this.phone = userData.phone || '';
						this.email = userData.email || '';
						this.gender = userData.gender;
						// 处理生日格式（可能是LocalDate字符串）
						if (userData.birthday) {
							this.birthday = userData.birthday.toString().substring(0, 10);
						} else {
							this.birthday = '';
						}
						this.level = userData.level || 1;
						
						// 更新本地存储
						Object.assign(user, userData);
						uni.setStorageSync('user', user);
					}
				}
			}).catch(err => {
				console.error('获取用户信息失败', err);
			});
		},
		
		// 选择头像
		chooseAvatar() {
			this.$u.route({
				url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
				params: {
					destWidth: 300,
					rectWidth: 200,
					fileType: 'jpg',
				}
			});
		},
		
		// 上传头像
		uploadAvatar(filePath) {
			uni.showLoading({
				title: '上传中...'
			});
			
			// 先上传文件
			uni.uploadFile({
				url: this.getBaseUrl() + '/api/file/file/upload',
				filePath: filePath,
				name: 'file',
				header: {
					Authorization: uni.getStorageSync('token') || ""
				},
				success: (uploadRes) => {
					try {
						const data = JSON.parse(uploadRes.data);
						if (data.code == 200) {
							// 兼容filePath和url字段
							const avatarUrl = data.data.filePath || data.data.url;
							this.avatar = avatarUrl;
							
							// 更新用户信息
							this.updateUserInfo({
								avatar: avatarUrl
							});
						} else {
							uni.hideLoading();
							this.$refs.uToast.show({
								title: data.message || '上传失败',
								type: 'error',
							});
						}
					} catch (e) {
						uni.hideLoading();
						this.$refs.uToast.show({
							title: '上传失败',
							type: 'error',
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					this.$refs.uToast.show({
						title: '上传失败',
						type: 'error',
					});
				}
			});
		},
		
		// 编辑昵称
		editNickname() {
			this.editNicknameValue = this.nickname;
			this.showNicknameModal = true;
			// 延迟设置焦点，确保弹窗已完全打开
			this.$nextTick(() => {
				setTimeout(() => {
					this.nicknameInputFocus = true;
					// 如果u-input不支持focus属性，尝试使用ref
					if (this.$refs.nicknameInput) {
						// u-input组件内部可能有input元素，尝试聚焦
						const inputEl = this.$refs.nicknameInput.$el?.querySelector('input');
						if (inputEl) {
							inputEl.focus();
						}
					}
				}, 300);
			});
		},
		
		// 昵称弹窗打开时的回调
		onNicknameModalOpen() {
			// 弹窗打开后自动聚焦输入框
			this.$nextTick(() => {
				setTimeout(() => {
					this.nicknameInputFocus = true;
					if (this.$refs.nicknameInput) {
						const inputEl = this.$refs.nicknameInput.$el?.querySelector('input');
						if (inputEl) {
							inputEl.focus();
						}
					}
				}, 300);
			});
		},
		
		// 昵称输入框获得焦点
		onNicknameInputFocus() {
			// 输入框获得焦点，确保输入法弹出
			this.nicknameInputFocus = true;
		},
		
		// 保存昵称
		saveNickname() {
			// 关闭焦点，避免输入法残留
			this.nicknameInputFocus = false;
			
			if (!this.editNicknameValue || this.editNicknameValue.trim() === '') {
				this.$refs.uToast.show({
					title: '昵称不能为空',
					type: 'error',
				});
				return;
			}
			
			this.updateUserInfo({
				nickname: this.editNicknameValue.trim()
			});
		},
		
		// 编辑邮箱
		editEmail() {
			this.editEmailValue = this.email;
			this.showEmailModal = true;
		},
		
		// 保存邮箱
		saveEmail() {
			if (!this.editEmailValue || this.editEmailValue.trim() === '') {
				this.$refs.uToast.show({
					title: '邮箱不能为空',
					type: 'error',
				});
				return;
			}
			
			// 简单的邮箱格式验证
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			if (!emailRegex.test(this.editEmailValue.trim())) {
				this.$refs.uToast.show({
					title: '邮箱格式不正确',
					type: 'error',
				});
				return;
			}
			
			this.updateUserInfo({
				email: this.editEmailValue.trim()
			});
		},
		
		// 编辑性别
		editGender() {
			this.showGenderSheet = true;
		},
		
		// 选择性别
		selectGender(index) {
			const selectedGender = this.genderList[index].value;
			this.updateUserInfo({
				gender: selectedGender
			});
		},
		
		// 编辑生日
		editBirthday() {
			this.showBirthdayPicker = true;
		},
		
		// 保存生日
		saveBirthday(e) {
			const dateStr = `${e.year}-${String(e.month).padStart(2, '0')}-${String(e.day).padStart(2, '0')}`;
			this.updateUserInfo({
				birthday: dateStr
			});
		},
		
		// 更新用户信息
		updateUserInfo(userInfo) {
			uni.showLoading({
				title: '保存中...'
			});
			
			const updateData = {
				userId: this.userId,
				...userInfo
			};
			
			this.$api.updateUserInfo(updateData).then(res => {
				uni.hideLoading();
				
				if (res.data && res.data.code === 200) {
					const updatedUser = res.data.data;
					
					// 更新本地数据
					if (userInfo.nickname !== undefined) {
						this.nickname = updatedUser.nickname || '';
					}
					if (userInfo.avatar !== undefined) {
						this.avatar = updatedUser.avatar || this.avatar;
					}
					if (userInfo.email !== undefined) {
						this.email = updatedUser.email || '';
					}
					if (userInfo.gender !== undefined) {
						this.gender = updatedUser.gender;
					}
					if (userInfo.birthday !== undefined) {
						// 处理生日格式（可能是LocalDate字符串）
						if (updatedUser.birthday) {
							this.birthday = updatedUser.birthday.toString().substring(0, 10);
						} else {
							this.birthday = '';
						}
					}
					
					// 更新本地存储
					const user = uni.getStorageSync('user');
					if (user) {
						Object.assign(user, updatedUser);
						uni.setStorageSync('user', user);
					}
					
					// 发送用户信息更新事件，通知其他页面同步
					uni.$emit('userInfoChanged', {
						avatar: updatedUser.avatar,
						nickname: updatedUser.nickname,
						gender: updatedUser.gender,
						email: updatedUser.email,
						birthday: updatedUser.birthday,
						level: updatedUser.level
					});
					
					// 关闭弹窗
					this.showNicknameModal = false;
					this.nicknameInputFocus = false; // 关闭焦点，隐藏输入法
					this.showEmailModal = false;
					this.showGenderSheet = false;
					this.showBirthdayPicker = false;
					
					this.$refs.uToast.show({
						title: '保存成功',
						type: 'success',
					});
				} else {
					this.$refs.uToast.show({
						title: res.data.message || '保存失败',
						type: 'error',
					});
				}
			}).catch(err => {
				uni.hideLoading();
				console.error('更新用户信息失败', err);
				this.$refs.uToast.show({
					title: '保存失败，请重试',
					type: 'error',
				});
			});
		},
		
		// 获取baseUrl
		getBaseUrl() {
			const config = require('../../config/config.js').default;
			let url = config.baseUrl || 'http://127.0.0.1:9401';
			// 确保URL格式正确
			if (url && !url.startsWith('http')) {
				url = 'http://' + url;
			}
			return url;
		},
		
		back() {
			// 返回到设置界面
			uni.navigateBack({
				delta: 1
			});
		},
		
		// 确定并返回我的界面
		confirmAndBack() {
			// 返回到"我的"界面（tabBar页面）
			uni.switchTab({
				url: '/pages/user/user'
			});
		},
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #fff;
}

.modal-content {
	padding: 20rpx;
}

.confirm-button-container {
	padding: 40rpx 30rpx;
	margin-top: 40rpx;
}
</style>
